package com.example.app.dialog

import android.content.Context
import androidx.core.view.isVisible
import cc.taylorzhang.singleclick.onSingleClick
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.StringUtils
import com.example.app.R
import com.example.app.base.BaseCenterDialog
import com.example.app.databinding.DialogCommonConfirmBinding
import com.lxj.xpopup.XPopup

class CommonConfirmDialog(context: Context) : BaseCenterDialog<DialogCommonConfirmBinding>(context) {

    override fun getViewBinding() = DialogCommonConfirmBinding.bind(popupImplView)
    override fun getImplLayoutId() = R.layout.dialog_common_confirm

    companion object {
        fun show(
            title: String? = "",
            content: String? = "",
            cancelText: String? = StringUtils.getString(R.string.cancel),
            confirmText: String? = StringUtils.getString(R.string.confirm),
            isShowCancelBtn: Boolean = true,
            onCancel: (() -> Unit)? = null,
            onConfirm: (() -> Unit)? = null
        ): CommonConfirmDialog? {
            ActivityUtils.getTopActivity()?.let {
                val dialog = CommonConfirmDialog(it).apply {
                    this.title = title ?: ""
                    this.content = content ?: ""
                    this.cancelText = cancelText ?: StringUtils.getString(R.string.cancel)
                    this.confirmText = confirmText ?: StringUtils.getString(R.string.confirm)
                    this.isShowCancelBtn = isShowCancelBtn
                    this.onCancel = onCancel
                    this.onConfirm = onConfirm
                }

                XPopup.Builder(it)
                    .isDestroyOnDismiss(true)
                    .asCustom(dialog)
                    .show()
                return dialog
            }
            return null
        }
    }

    private var title = ""
    private var content = ""
    private var cancelText = ""
    private var confirmText = ""
    private var isShowCancelBtn = true
    private var onCancel: (() -> Unit)? = null
    private var onConfirm: (() -> Unit)? = null

    override fun onCreate() {
        super.onCreate()
        mViewBinding?.apply {
            tvTitle.text = title
            tvTitle.isVisible = title.isNotEmpty()

            tvContent.text = content
            tvContent.isVisible = content.isNotEmpty()

            tvCancel.text = cancelText
            tvConfirm.text = confirmText

            tvCancel.isVisible = isShowCancelBtn

            tvCancel.onSingleClick {
                onCancel?.invoke()
                dismiss()
            }
            tvConfirm.onSingleClick {
                onConfirm?.invoke()
                dismiss()
            }
        }
    }
}